/**
 * 
 */
package travibot.engine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * @author Petr Macek
 * 
 */
public class TaskQueue {

    private PriorityBlockingQueue<Task> queuedTasks = new PriorityBlockingQueue<Task>();
    
    private Vector<ScheduledTask> scheduledTasks = new Vector<ScheduledTask>();

    public synchronized void addTask(Task task) {
        
        if(task instanceof ScheduledTask){            
            scheduledTasks.add((ScheduledTask)task);
        } else {
            queuedTasks.add(task);
        }        
    }

    /**
     * Gets task on the head of the queue. If there is conflicting scheduled
     * task, the scheduled task is returned first.
     * After returning the task is removed fro the queue.
     * 
     * @return Task on the head of the queue. Null is returned if there is none.
     */
    public synchronized Task getCurrentTask() {

        Task ret = null;
        Date currentDate = new Date();
        List<ScheduledTask> scheduled = getSortedScheduledTasks();
        if (scheduled != null && scheduled.size() >= 1) {
            ScheduledTask task = scheduled.get(0);
            if (task != null && task.getScheduledTime().compareTo(currentDate) < 0) {
                ret = task;
                scheduled.remove(task);
            }
            else {
                ret = queuedTasks.poll();
            }
        }
        else {
            ret = queuedTasks.poll();
        }
        return ret;
    }
    
    public synchronized boolean isEmpty(){
        boolean ret = false;
        if(scheduledTasks.isEmpty() && queuedTasks.isEmpty()){
            ret = true;
        }
        return ret;
    }
    
    private List<ScheduledTask> getSortedScheduledTasks(){
        Collections.sort(scheduledTasks);
        return scheduledTasks;
    }
    
    /**
     * Gets the list of all task without removing them from the queue
     * @return
     */
    public synchronized List<Task> getTaskList(){
        List<Task> list = new ArrayList<Task>();
        list.addAll(getSortedScheduledTasks());
        Iterator<Task> queueIt =  queuedTasks.iterator();
        while(queueIt.hasNext()){
            list.add(queueIt.next());
        }        
        return list;
    }

}
